<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        label="手机号码"
        required
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请输入正确的手机号',
            trigger: 'onChange',
            pattern: /^1[3-9]\d{0,9}$/,
          },
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="登录密码"
        required
        placeholder="请输入密码"
        :rules="[
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="拼命登录ing..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      formLogin: {
        mobile: '16666666666', // 手机号
        code: '246810' // 后台只能用这个密码
      },
      isLoading: false // 按钮加载状态
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    // 点击登录
    async onSubmit () {
      this.isLoading = true // 按钮加载效果
      try {
        const res = await loginAPI(this.formLogin)
        this.setToken(res.data.data.token)
        this.setRefreshToken(res.data.data.refresh_token)
        console.log(res)
        this.isLoading = false
        Notify({ type: 'success', message: '登录成功啦!' })
        // 跳转到/layout
        this.$router.push({
          path: '/layout'
          // path: '/layout/home' // 这3种写法都OK
          // name: 'Layout'
        })
      } catch (err) {
        // 如果登录失败了, 也要把按钮放开
        this.isLoading = false
        Notify({ type: 'warning', message: '登录失败了T.T' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
// .van-nav-bar {
//   background-color: #007bff;
// }
// // 知识点1: 组件内的标签不会被scoped影响添加data-v属性
// // 选择组件内的标签, 要用/deep/ 后代选择器
// /deep/ .van-nav-bar__title {
//   color: white;
// }
</style>
